﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace CommonLib {
    public class Screen {
        private Vector3 topLeft;
        private int width, height, length;
        private Vector3 dw, dh;
        private Vector3 eye;
        private Bitmap pixels;

        public Screen(Vector3 tl, Vector3 tr, Vector3 bl, int w, int h, Vector3 ey) {
            this.topLeft = tl;
            this.width = w;
            this.height = h;
            this.length = w * h;
            this.eye = ey;
            pixels = new Bitmap(w, h);

            this.dw = new Vector3(tr);
            this.dw.sub(tl);
            this.dw.div(w);

            this.dh = new Vector3(bl);
            this.dh.sub(tl);
            this.dh.div(h);
        }
        public Bitmap Buffer {
            get { return this.pixels; }
        }
        public int getSize() {
            return this.length;
        }
        public Ray assignRay(int w, int h, Ray r) {
            r.Eye.set(this.eye);
            for (int i = 0; i < topLeft.Length; i++) {
                r.Dir[i] = topLeft[i] + (dw[i] * w) + (dh[i] * h) - r.Eye[i];
            }
            return r.normalize();
        }
        public Ray assignRay(int index, Ray r) {
            return assignRay(index % width, index / width, r);
        }
        public void setPixel(int w, int h, Vector3 color) {
            this.pixels.SetPixel(w, h, Color.FromArgb(
                (int)(Math.Max(0.0, Math.Min(color[0], 1.0)) * 255),
                (int)(Math.Max(0.0, Math.Min(color[1], 1.0)) * 255),
                (int)(Math.Max(0.0, Math.Min(color[2], 1.0)) * 255)) );
        }
        public void setPixel(int index, Vector3 color) {
            setPixel(index % width, index / width, color);
        }
    }
}
